import {
  createUser,
  getUserBalanceRecord,
  getUserCreditRecord,
  getUserList,
  updateUserBalance,
  updateUserCredit,
} from '@/services/ant-design-pro/menber';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProTable,
  useDebounceFn,
} from '@ant-design/pro-components';
import { FormattedMessage } from '@umijs/max';
import { Button, Col, Drawer, Input, message, Modal, Row, Table } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import type { FormValueType } from './components/UpdateForm';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.RuleListItem) => {
  const hide = message.loading('正在添加');
  try {
    await createUser({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败，请重试。');
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('更新中');
  console.log('[fields]', fields);
  try {
    await updateUserBalance(fields?.id, { ...fields });
    hide();

    message.success('编辑成功');
    return true;
  } catch (error) {
    hide();
    message.error('编辑失败');
    return false;
  }
};

const handleUpdateCredit = async (fields: FormValueType) => {
  const hide = message.loading('更新中');
  console.log('[fields]', fields);
  try {
    await updateUserCredit(fields?.id, { ...fields });
    hide();

    message.success('编辑成功');
    return true;
  } catch (error) {
    hide();
    message.error('编辑失败');
    return false;
  }
};

const MenberList: React.FC = () => {
  const [dataSource, setDataSource] = useState([]);
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  const [valUpdateType, setValUpdateType] = useState('add');

  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const [updateModalOpen2, handleUpdateModalOpen2] = useState<boolean>(false);

  const [detailModalOpen, handleDetailModalOpen] = useState<boolean>(false);
  const [balanceList, setBalanceList] = useState([]);
  const [detailModalOpen2, handleDetailModalOpen2] = useState<boolean>(false);
  const [creditList, setCreditList] = useState([]);
  const [searchParams, setSearchParams] = useState({});

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();

  const columns: ProColumns<API.RuleListItem>[] = [
    {
      search: false,
      title: '昵称',
      dataIndex: 'username',
    },
    {
      search: false,
      title: '手机号',
      dataIndex: 'mobile',
    },
    {
      search: false,
      title: '余额',
      dataIndex: 'balance',
    },
    {
      search: false,
      title: '积分',
      dataIndex: 'credit',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalOpen(true);
            setCurrentRow({ ...record });
          }}
        >
          更新余额
        </a>,
        <a
          key="config"
          onClick={async () => {
            handleDetailModalOpen(true);
            const resp = await getUserBalanceRecord(record.id);
            setBalanceList(resp?.data?.list);
          }}
        >
          余额历史记录
        </a>,
        <a
          key="config"
          onClick={() => {
            handleUpdateModalOpen2(true);
            setCurrentRow({ ...record });
          }}
        >
          更新积分
        </a>,
        <a
          key="config"
          onClick={async () => {
            handleDetailModalOpen2(true);
            const resp = await getUserCreditRecord(record.id);
            setCreditList(resp?.data?.list);
          }}
        >
          积分历史记录
        </a>,
        // <Popconfirm
        //   title="确认删除吗"
        //   key="delete"
        //   onConfirm={async () => {
        //     await deleteUser(record.id);
        //     init();
        //   }}
        // >
        //   <a>删除</a>
        // </Popconfirm>,
      ],
    },
  ];

  const balanceColumns = [
    {
      search: false,
      title: '余额操作',
      dataIndex: 'amount',
    },
    {
      search: false,
      title: '时间',
      dataIndex: 'createdAt',
    },
  ];

  const init = async (params = {}) => {
    const resp = await getUserList({ ...params, page: 1, pageSize: 50 });

    console.log('[resp]', resp);
    const { list } = resp?.data;
    setDataSource(list);
  };

  const { run: handleSearch } = useDebounceFn((params) => {
    setSearchParams({ ...searchParams, ...params });
    return init({ ...searchParams, ...params });
  }, 500);

  useEffect(() => {
    init();
  }, []);

  return (
    <PageContainer>
      <Modal open={detailModalOpen} onCancel={() => handleDetailModalOpen(false)} footer={null}>
        <Table dataSource={balanceList} columns={balanceColumns}></Table>
      </Modal>

      <Modal open={detailModalOpen2} onCancel={() => handleDetailModalOpen2(false)} footer={null}>
        <Table dataSource={creditList} columns={balanceColumns}></Table>
      </Modal>

      <ProTable<API.RuleListItem, API.PageParams>
        actionRef={actionRef}
        rowKey="key"
        search={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
        ]}
        toolbar={{
          search: (
            <Row gutter={10}>
              <Col>
                <Input
                  placeholder="请输入手机号"
                  onChange={(e) => {
                    handleSearch({
                      keyword: e.target.value,
                    });
                  }}
                ></Input>
              </Col>
            </Row>
          ),
        }}
        dataSource={dataSource}
        columns={columns}
        // rowSelection={{
        //   onChange: (_, selectedRows) => {
        //     setSelectedRows(selectedRows);
        //   },
        // }}
        onLoad={init}
        options={false}
      />
      <ModalForm
        title={'新建'}
        width="400px"
        modalProps={{
          destroyOnClose: true,
        }}
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          const success = await handleAdd(value as API.RuleListItem);
          if (success) {
            handleModalOpen(false);
            init();
          }
        }}
      >
        <ProFormText
          label="手机号"
          rules={[
            {
              required: true,
            },
          ]}
          width="md"
          name="mobile"
        />
      </ModalForm>

      <ModalForm
        title={'更新余额'}
        modalProps={{
          destroyOnClose: true,
        }}
        width="400px"
        open={updateModalOpen}
        onOpenChange={(vis) => {
          handleUpdateModalOpen(vis);
          if (!vis) {
            setCurrentRow(undefined);
            setValUpdateType('add');
          }
        }}
        onFinish={async (value) => {
          const success = await handleUpdate({
            id: currentRow?.id,
            ...value,
            balance: value?.opType === 'add' ? value?.balance : -value?.balance,
          });
          if (success) {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            init();
          }
        }}
        initialValues={currentRow}
      >
        <ProFormSelect
          label="操作类型"
          name={'opType'}
          initialValue={valUpdateType}
          options={[
            {
              label: '增加',
              value: 'add',
            },
            {
              label: '减少',
              value: 'reduce',
            },
          ]}
          onChange={(val) => {
            setValUpdateType(val);
          }}
          rules={[
            {
              required: true,
            },
          ]}
          allowClear={false}
        ></ProFormSelect>
        <ProFormDigit
          label="余额"
          rules={[
            {
              required: true,
            },
          ]}
          width="md"
          name="balance"
        />
      </ModalForm>
      <ModalForm
        title={'更新积分'}
        modalProps={{
          destroyOnClose: true,
        }}
        width="400px"
        open={updateModalOpen2}
        onOpenChange={(vis) => {
          handleUpdateModalOpen2(vis);
          if (!vis) {
            setCurrentRow(undefined);
            setValUpdateType('add');
          }
        }}
        onFinish={async (value) => {
          const success = await handleUpdateCredit({
            id: currentRow?.id,
            ...value,
            credit: value?.opType === 'add' ? value?.credit : -value?.credit,
          });
          if (success) {
            handleUpdateModalOpen2(false);
            setCurrentRow(undefined);
            init();
          }
        }}
        initialValues={currentRow}
      >
        <ProFormSelect
          label="操作类型"
          name={'opType'}
          initialValue={valUpdateType}
          options={[
            {
              label: '增加',
              value: 'add',
            },
            {
              label: '减少',
              value: 'reduce',
            },
          ]}
          onChange={(val) => {
            setValUpdateType(val);
          }}
          rules={[
            {
              required: true,
            },
          ]}
          allowClear={false}
        ></ProFormSelect>
        <ProFormDigit
          label="积分"
          rules={[
            {
              required: true,
            },
          ]}
          width="md"
          name="credit"
        />
      </ModalForm>

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default MenberList;
